/*
* @Author: gaara  
* @Date: 2020-06-13 14:17:52  
*/

import _fs from 'fs-extra'
import _path from 'path'
import { v4 as uuidv4 } from 'uuid';

export class UuidMgr {
    /** meta数据 */
    static uuidMap: { [uuid: string]: string } = {};
    static pathMap: { [path: string]: string } = {};

    private static getObjMeta(obj: any, fullPath: string) {
        let getUuid = obj['uuid'];
        if (getUuid) {
            let srcPath = fullPath.replace(".meta","");
            UuidMgr.uuidMap[getUuid] = srcPath;
            UuidMgr.pathMap[srcPath] = getUuid;
        }

        let subMetas = obj['subMetas'];
        if (subMetas) {
            for (const key in subMetas) {
                let sub = subMetas[key];
                let p = _path.join(fullPath, key);
                UuidMgr.getObjMeta(sub, p);
            }
        }
    }

    /**
     * 递归遍历,获得meta文件
     * @param dir 
     */
    static walkDirGetMeta(dic: string): void {
        let files = _fs.readdirSync(dic);

        files.forEach((path: string) => {

            let fullPath = _path.join(dic, path);

            if (_fs.statSync(fullPath).isDirectory()) {
                UuidMgr.walkDirGetMeta(fullPath);
            }
            else if (_path.extname(path) == '.meta') {
                try {
                    let json = _fs.readJSONSync(fullPath);
                    UuidMgr.getObjMeta(json, fullPath);
                } catch (error) {

                }
            }
        });
    }

    /**
     * 给路径创建UUID
     */
    static getUUID(p: string): string {
        p = p.replace(".meta","");

        let uuid = "";
        if(!UuidMgr.pathMap[p]){
            uuid = uuidv4();
            while (UuidMgr.uuidMap[uuid]) {
                uuid = uuidv4();
            }
    
            UuidMgr.uuidMap[uuid] = p;
            UuidMgr.pathMap[p] = uuid;
        }

        uuid = UuidMgr.pathMap[p];

        return uuid;
    }
}